<template>
  <div class="demo">
    <div class="demo-title">动态校验规则</div>
    <div class="demo-content">
      <Form ref="formRef" :model="formState" name="dynamic_rule" v-bind="formItemLayout">
        <Form.Item
          label="Username"
          name="username"
          :rules="[{ required: true, message: 'Please input your username!' }]"
        >
          <Input v-model:value="formState.username" />
        </Form.Item>
        <Form.Item
          label="Nickname"
          name="nickname"
          :rules="[{ required: formState.checkNick, message: 'Please input your nickname!' }]"
        >
          <Input v-model:value="formState.nickname" />
        </Form.Item>
        <Form.Item name="checkNick" v-bind="formTailLayout">
          <Checkbox v-model:checked="formState.checkNick">Nickname is required</Checkbox>
        </Form.Item>
        <Form.Item v-bind="formTailLayout">
          <Button type="primary" @click="onCheck">Check</Button>
        </Form.Item>
      </Form>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { reactive, ref, watch } from 'vue';
  import Button from '@sscd/button';
  import Checkbox from '@sscd/checkbox';
  import Input from '@sscd/input';
  import Form from '@sscd/form';
  import type { FormInstance } from '@sscd/form';
  interface FormState {
    username: string;
    nickname: string;
    checkNick: boolean;
  }
  const formRef = ref<FormInstance>();
  const formState = reactive<FormState>({
    username: '',
    nickname: '',
    checkNick: false,
  });
  watch(
    () => formState.checkNick,
    () => formRef.value?.validateFields(['nickname']),
    { flush: 'post' }
  );
  const onCheck = async () => {
    try {
      const values = await formRef.value?.validateFields();
      console.log('Success:', values);
    } catch (errorInfo) {
      console.log('Failed:', errorInfo);
    }
  };
  const formItemLayout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 8 },
  };
  const formTailLayout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 8, offset: 4 },
  };
</script>
